"use strict";
define(["commonUI", "laydate", "template","global", "validate", "select2", "ztree", "plupload"], function (
    commonUI, laydate, template,global
) {
    var user = null;
    var app = {
        init: function () {
          user = global.getLoginUser();
          $(".username").text(user.userName);
          //初始化通用数据项
          this.initCommonDataItem();
          //初始化可再生能源利用量
          this.initRenewableEnergy();
          //初始化能耗占比
          this.initPowercostRate();
          //初始化制冷能耗、供暖能耗
          this.initCoolingAndHeating();
          //初始化制冷、供暖SCOP
          this.initSCOP();
          this.eventBind();
        },
        initCommonDataItem:function(){
          $("#div1").html("");
            global.get("/admin/statisticsConfig/dataConfig/list/",function(response){
              response.data.commonDataConfigList.forEach(element=>{
                var str = element.name + "="
                element.deviceNames.forEach(name=>{
                  str += name + "+";
                })
                str = str.substr(0,str.length-1)
                $("#div1").append('<div class="info-con"><div class="info-header"><span class="info-header-text">'+element.name+'</span><a class="edit-btn pull-right" data-type="1" data-id="'+element.id+'" data-name="'+element.name+'"><i class="aidicon aidicon-clipboard-check"></i>编辑</a><a class="del-btn pull-right" dataConfigId="'+element.id+'" type="commonDataConfig"><i class="aidicon aidicon-delete"></i>删除</a></div><div class="info-wrap text-overflow" title="'+str+'">'+str+'</div></div>')
              })
            })
        },
        initRenewableEnergy:function(){
          $("#div2").html("");
          global.get("/admin/statisticsConfig/statisticsConfig/plusDetailShowGlobal?statisticsTypeId=5",function(response){
            var names=response.data.names;
            var str="可再生能源利用量="
            if(names!=null){
              names.forEach(element=>{
                str += element + "+";
              });
            }
            str = str.substr(0,str.length-1);
            $("#div2").append('<div class="info-con"><div class="info-header"><span class="info-header-text">可再生能源利用量</span><a class="edit-btn pull-right" data-id="s5" data-type="2"><i class="aidicon aidicon-clipboard-check"></i>编辑</a></div><div class="info-wrap text-overflow" title="'+str+'">'+str+'</div></div>')
          });
        },
        initPowercostRate:function(){
          $("#div3").html("");
          global.get("/admin/statisticsConfig/powercostRateConfig/list",function(response){
            var fenmu = "";
            response.data.rateTypes.forEach(element=>{
              element.deviceNames.forEach(name=>{
                fenmu += name + "+";
              })
            })
            fenmu = fenmu.substr(0,fenmu.length-1)
            response.data.rateTypes.forEach(element=>{
              var fenzi = "";
              element.deviceNames.forEach(name=>{
                fenzi += name + "+";
              })
              fenzi = fenzi.substr(0,fenzi.length-1)
              $("#div3").append('<div class="info-con"><div class="info-header"><span class="info-header-text">'+element.name+'</span><a class="edit-btn pull-right" data-name="'+element.name+'" data-id="r'+element.id+'" data-type="3"><i class="aidicon aidicon-clipboard-check"></i>编辑</a><a class="del-btn pull-right" type="rateType" rateTypeId="'+element.id+'"><i class="aidicon aidicon-delete"></i>删除</a></div><div class="info-box"><div class="info-label">'+element.name+'=</div><div class="info-percent"><div class="info-num text-overflow" title="'+fenzi+'">'+fenzi+'</div><div class="split-line"></div><div class="info-num text-overflow" title="'+fenmu+'">'+fenmu+'</div></div></div></div></div>')
            })
          })
        },
        initCoolingAndHeating:function(){
          $("#div4").html("");
          global.get("/admin/statisticsConfig/statisticsConfig/plusDetailShowGlobal?statisticsTypeId=13",function(response){
            var names=response.data.names;
            var str="制冷/供暖能耗="
            if(names!=null){
              names.forEach(element=>{
                str += element + "+";
              });
            }
            str = str.substr(0,str.length-1);
            $("#div4").append('<div class="info-con"><div class="info-header"><span class="info-header-text">制冷/供暖能耗</span><a class="edit-btn pull-right" data-id="s13" data-type="4"><i class="aidicon aidicon-clipboard-check"></i>编辑</a></div><div class="info-wrap text-overflow" title="'+str+'">'+str+'</div></div>')
          },null,null,false);
          // global.get("/admin/statisticsConfig/statisticsConfig/plusDetailShowGlobal?statisticsTypeId=14",function(response){
          //   var names=response.data.names;
          //   var str="供暖能耗="
          //   if(names!=null){
          //     names.forEach(element=>{
          //       str += element + "+";
          //     });
          //   }
          //   str = str.substr(0,str.length-1);
          //   $("#div4").append('<div class="info-con"><div class="info-header"><span class="info-header-text">供暖能耗</span><a class="edit-btn pull-right" data-id="s14" data-type="4"><i class="aidicon aidicon-clipboard-check"></i>编辑</a></div><div class="info-wrap text-overflow" title="'+str+'">'+str+'</div></div>')
          // },null,null,false);
        },
        initSCOP:function(){
          $("#div5").html("");
          global.get("/admin/statisticsConfig/statisticsConfig/plusDetailShowGlobal?statisticsTypeId=17",function(response){
            var names=response.data.names;
            var str=""
            if(names!=null){
              names.forEach(element=>{
                str += element + "+";
              });
            }
            str = str.substr(0,str.length-1);
            $("#div5").append('<div class="info-con"><div class="info-header"><span class="info-header-text">制冷SCOP</span><a class="edit-btn pull-right" data-id="s17" data-type="6"><i class="aidicon aidicon-clipboard-check"></i>编辑</a></div><div class="info-box"><div class="info-label">制冷SCOP=</div><div class="info-percent"><div class="info-num text-overflow" title="'+str+'">'+str+'</div><div class="split-line"></div><div class="info-num text-overflow" title="">制冷/供暖能耗</div></div></div></div>')
          },null,null,false);
          global.get("/admin/statisticsConfig/statisticsConfig/plusDetailShowGlobal?statisticsTypeId=18",function(response){
            var names=response.data.names;
            var str=""
            if(names!=null){
              names.forEach(element=>{
                str += element + "+";
              });
            }
            str = str.substr(0,str.length-1);
            $("#div5").append('<div class="info-con"><div class="info-header"><span class="info-header-text">供暖SCOP</span><a class="edit-btn pull-right" data-id="s18" data-type="6"><i class="aidicon aidicon-clipboard-check"></i>编辑</a></div><div class="info-box"><div class="info-label">供暖SCOP=</div><div class="info-percent"><div class="info-num text-overflow" title="'+str+'">'+str+'</div><div class="split-line"></div><div class="info-num text-overflow" title="">制冷/供暖能耗</div></div></div></div>')
          },null,null,false);
        },
        initInputSelect: function (id,type,num) {
          $("#dropdownSelect-treeSelect-multi"+id).dropdownSelect({container:'body',type: 'multi'});
          var setting = {
              check: {
                  enable: true
              },
              data: {
                  simpleData: {
                      enable: true
                  }
              },
              callback:{
                  onCheck:onCheck
              }
          };
          var zNodes =[];
          if(type==0){
            var dataId = "";
            if(num!=null){
              dataId = "?dataId="+num;
            }
            global.get("/admin/statisticsConfig/allDevice/list"+dataId,function(response){
              response.data.list.forEach(function(element){
                zNodes.push({
                  id:"p"+element.title,
                  name:element.title,
                  open:false
                });
                element.devices.forEach(device=>{
                  zNodes.push({
                    id:device.deviceId,
                    name:device.deviceName,
                    pId:"p"+element.title,
                    checked:device.selected,
                    open:false
                  });
                });
              });
            },null,null,false)
          }else if(type==1){
            var dataId="";
            if(num!=null){
              dataId="?dataId="+num;
            }
            global.get("/admin/statisticsConfig/allDeviceAndDataConfig/list"+dataId,function(response){
              response.data.list.forEach(element=>{
                if(element.type=="commonDataConfig"){
                  zNodes.push({
                    id:"c"+element.title,
                    name:element.title,
                    open:false
                  });
                  element.dataConfigs.forEach(item=>{
                    zNodes.push({
                      id:item.deviceId,
                      name:item.deviceName,
                      pId:"c"+element.title,
                      checked:item.selected,
                      open:false
                    })
                  })
                }else{
                  zNodes.push({
                    id:"d"+element.title,
                    name:element.title,
                    open:false
                  });
                  element.devices.forEach(item=>{
                    zNodes.push({
                      id:item.deviceId,
                      name:item.deviceName,
                      pId:"d"+element.title,
                      checked:item.selected,
                      open:false
                    });
                  });
                }
              });
            },null,null,false)
          }
          var treeSelectObj2 = $.fn.zTree.init($("#treeDemo-"+id), setting, zNodes);
          function onCheck(){
              var nodes = treeSelectObj2.getCheckedNodes(true);
              var checkedNodes = [];
              for(var i = 0; i < nodes.length; i++){
                  var obj = {};
                  obj['text'] = nodes[i]['name'];
                  obj['value'] = nodes[i]['name'];
                  checkedNodes.push(obj);
              }
              $("#dropdownSelect-treeSelect-multi"+id).dropdownSelect("setChecked",checkedNodes);
          }
          $('#dropdownSelect-treeSelect-multi'+id).on('removen.bs.dropdownSelect', function (e) {
              var tree = $.fn.zTree.getZTreeObj('treeDemo-'+id);
              var objs =  _.where(tree.getCheckedNodes(true), { 'name': e.value});
              var obj = objs[0];
              tree.checkNode(obj,false,true);
              onCheck();
          })
          return treeSelectObj2;
        },
        /** 事件绑定 */
        eventBind: function () {
            // 新增
            var treeSelect = null;
            $('#add1').on('click', function () {
              Dialog.open({
                theme: "addFormDialog",
                id: 'dialog-example11',
                title: '新增通用数据项配置',
                width: 480,
                height: 320,
                modal: true,
                context: self,
                content: template("addFormTpl",{type: 1}),
                onShow: function () {
                  treeSelect=app.initInputSelect(29,0);
                },
                onClosed: function () {
                  $(".dropdownSelect-menu").remove();
                },
                button: [
                  { id: "mybtn1", label: "保存", intent: "primary", focus: true, click: function () {
                    if (!$(".addForm").valid()) {
                      return false;
                    }
                    var deviceIds = [];
                    treeSelect.getCheckedNodes().forEach(element=>{
                      if(element.pId!=null){
                        deviceIds.push(element.id);
                      }
                    });
                    var name = $("#prjId").val();
                    global.post("/admin/statisticsConfig/dataConfig/config?name="+name + "&deviceIds="+deviceIds,function(response){
                      if(response.success){
                          Dialog.toast("操作成功", {"intent":"success"});
                          app.initCommonDataItem();
                        }else{
                          Dialog.toast(response.message, {"intent":"warn"});
                        }
                    })
                   } },
                  { id: "mybtn2", label: "取消", click: function () { } }
              ]
              });
            });
            $('#add3').on('click', function () {
              var treeSelect = null;
              Dialog.open({
                theme: "addFormDialog",
                id: 'dialog-example11',
                title: '新增能耗占比类别',
                width: 480,
                height: 320,
                modal: true,
                context: self,
                content: template("addFormTpl",{type: 3}),
                onShow: function () {
                    treeSelect = app.initInputSelect(29,1);
                },
                onClosed: function () {
                  $(".dropdownSelect-menu").remove();
                },
                button: [
                  { id: "mybtn1", label: "保存", intent: "primary", focus: true, click: function () { 
                    if (!$(".addForm").valid()) {
                      return false;
                    }
                    var rateName=$("#prjId").val();
                    var nodes = treeSelect.getCheckedNodes(true);
                    var deviceIds = [];
                    var dataConfigIds = [];
                    nodes.forEach(element=>{
                      if(element.pId!=null){
                        if(element.pId[0]=="c"){
                          dataConfigIds.push(element.id);
                        }else if(element.pId[0]=="d"){
                          deviceIds.push(element.id);
                        }
                      }
                    })
                    global.post("/admin/statisticsConfig/powercostRateConfig/config?rateName="+rateName + "&deviceIds="+deviceIds + "&dataConfigIds="+dataConfigIds,response=>{
                      if(response.success){
                        Dialog.toast("操作成功", {"intent":"success"});
                        app.initPowercostRate();
                      }else{
                        Dialog.toast(response.message, {"intent":"warn"});
                      }
                     })
                  } },
                  { id: "mybtn2", label: "取消", click: function () { } }
              ]
              });
            });
            // 编辑
            $(document).on("click", ".edit-btn", function () {
                var code=$(this).data("type");
                var title = $(this).parents(".info-header").find(".info-header-text").text();
                //通用配置项编辑
                if(code==1) {
                  var treeSelect = null;
                  var name = $(this).data("name");
                  var dataId = $(this).data("id");
                  Dialog.open({
                    theme: "addFormDialog",
                    id: 'dialog-example11',
                    title: '编辑'+title,
                    width: 480,
                    height: 320,
                    modal: true,
                    context: self,
                    content: template("addFormTpl",{type: 1,name:name}),
                    onShow: function () {
                        treeSelect = app.initInputSelect(29,0,dataId);
                    },
                    onClosed: function () {
                      $(".dropdownSelect-menu").remove();
                    },
                    button: [
                      { id: "mybtn1", label: "保存", intent: "primary", focus: true, click: function () { 
                        if (!$(".addForm").valid()) {
                          return false;
                        }
                        var deviceIds = [];
                        treeSelect.getCheckedNodes().forEach(element=>{
                          if(element.pId!=null){
                            deviceIds.push(element.id);
                          }
                        });
                        var name = $("#prjId").val();
                        global.post("/admin/statisticsConfig/dataConfig/config?name="+name + "&deviceIds="+deviceIds,function(response){
                          if(response.success){
                              Dialog.toast("操作成功", {"intent":"success"});
                              app.initCommonDataItem();
                            }else{
                              Dialog.toast(response.message, {"intent":"warn"});
                            }
                        })
                      } },
                      { id: "mybtn2", label: "取消", click: function () { } }
                    ]
                  });
                } else if (code==2) {
                  var treeSelect = null;
                  var dataId = $(this).data("id");
                  Dialog.open({
                    theme: "addFormDialog",
                    id: 'dialog-example11',
                    title: '编辑可再生能源利用量',
                    width: 480,
                    height: 280,
                    modal: true,
                    context: self,
                    content: template("addFormTpl",{type: 2}),
                    onShow: function () {
                        treeSelect=app.initInputSelect(29,1,dataId);
                    },
                    onClosed: function () {
                      $(".dropdownSelect-menu").remove();
                    },
                    button: [
                      { id: "mybtn1", label: "保存", intent: "primary", focus: true, click: function () { 
                        if (!$(".addForm").valid()) {
                          return false;
                        }
                        var nodes = treeSelect.getCheckedNodes(true);
                        var deviceIds = [];
                        var dataConfigIds = [];
                        nodes.forEach(element=>{
                          if(element.pId!=null){
                            if(element.pId[0]=="c"){
                              dataConfigIds.push(element.id);
                            }else if(element.pId[0]=="d"){
                              deviceIds.push(element.id);
                            }
                          }
                        })
                        global.post("/admin/statisticsConfig/statisticsConfig/configGlobal?statisticsTypeId=5&deviceIds="+deviceIds+"&dataConfigIds="+dataConfigIds,function(response){
                          if(response.success){
                              Dialog.toast("操作成功", {"intent":"success"});
                              app.initRenewableEnergy();
                            }else{
                              Dialog.toast(response.message, {"intent":"warn"});
                            }
                        })
                      } },
                      { id: "mybtn2", label: "取消", click: function () { } }
                    ]
                  });
                } else if (code==3) {
                  var treeSelect = null;
                  var name = $(this).data("name");
                  var dataId = $(this).data("id");
                  Dialog.open({
                    theme: "addFormDialog",
                    id: 'dialog-example11',
                    title: '编辑'+title,
                    width: 480,
                    height: 320,
                    modal: true,
                    context: self,
                    content: template("addFormTpl",{type: 3,name:name}),
                    onShow: function () {
                        treeSelect = app.initInputSelect(29,1,dataId);
                    },
                    onClosed: function () {
                      $(".dropdownSelect-menu").remove();
                    },
                    button: [
                      { id: "mybtn1", label: "保存", intent: "primary", focus: true, click: function () { 
                        if (!$(".addForm").valid()) {
                          return false;
                        }
                        var rateName=$("#prjId").val();
                        var nodes = treeSelect.getCheckedNodes(true);
                        var deviceIds = [];
                        var dataConfigIds = [];
                        nodes.forEach(element=>{
                          if(element.pId!=null){
                            if(element.pId[0]=="c"){
                              dataConfigIds.push(element.id);
                            }else if(element.pId[0]=="d"){
                              deviceIds.push(element.id);
                            }
                          }
                        })
                        global.post("/admin/statisticsConfig/powercostRateConfig/config?rateName="+rateName + "&deviceIds="+deviceIds + "&dataConfigIds="+dataConfigIds,response=>{
                          if(response.success){
                            Dialog.toast("操作成功", {"intent":"success"});
                            app.initPowercostRate();
                          }else{
                            Dialog.toast(response.message, {"intent":"warn"});
                          }
                         })
                      } },
                      { id: "mybtn2", label: "取消", click: function () { } }
                    ]
                  });
                } else if (code==4) {
                  var dataId = $(this).data("id");
                  var treeSelect = null;
                  var title = $(this).parents(".info-header").find(".info-header-text").text();
                  Dialog.open({
                    theme: "addFormDialog",
                    id: 'dialog-example11',
                    title: '编辑'+title,
                    width: 480,
                    height: 280,
                    modal: true,
                    context: self,
                    content: template("addFormTpl",{type: 2}),
                    onShow: function () {
                        treeSelect = app.initInputSelect(29,1,dataId);
                    },
                    onClosed: function () {
                      $(".dropdownSelect-menu").remove();
                    },
                    button: [
                      { id: "mybtn1", label: "保存", intent: "primary", focus: true, click: function () { 
                        var num;
                        if(title=="制冷能耗"){
                          num = 13;
                        }else if(title=="供暖能耗"){
                          num=14;
                        }
                        var nodes = treeSelect.getCheckedNodes(true);
                        var deviceIds = [];
                        var dataConfigIds = [];
                        nodes.forEach(element=>{
                          if(element.pId!=null){
                            if(element.pId[0]=="c"){
                              dataConfigIds.push(element.id);
                            }else if(element.pId[0]=="d"){
                              deviceIds.push(element.id);
                            }
                          }
                        })
                        global.post("/admin/statisticsConfig/statisticsConfig/configGlobal?statisticsTypeId="+num+"&deviceIds="+deviceIds+"&dataConfigIds="+dataConfigIds,function(response){
                          if(response.success){
                              Dialog.toast("操作成功", {"intent":"success"});
                              app.initCoolingAndHeating();
                            }else{
                              Dialog.toast(response.message, {"intent":"warn"});
                            }
                        })

                      } },
                      { id: "mybtn2", label: "取消", click: function () { } }
                    ]
                  });
                } else if (code==6) {
                  var dataId = $(this).data("id");
                  var treeSelect = null;
                  var title = $(this).parents(".info-header").find(".info-header-text").text();
                  Dialog.open({
                    theme: "addFormDialog",
                    id: 'dialog-example11',
                    title: '编辑'+title,
                    width: 480,
                    height: 250,
                    modal: true,
                    context: self,
                    content: template("addFormTpl",{type: 4}),
                    onShow: function () {
                        treeSelect = app.initInputSelect(30,1,dataId);
                    },
                    onClosed: function () {
                      $(".dropdownSelect-menu").remove();
                    },
                    button: [
                      { id: "mybtn1", label: "保存", intent: "primary", focus: true, click: function () { 
                        var num;
                        if(title=="制冷SCOP"){
                          num = 17;
                        }else if(title=="供暖SCOP"){
                          num=18;
                        }
                        var nodes = treeSelect.getCheckedNodes(true);
                        var deviceIds = [];
                        var dataConfigIds = [];
                        nodes.forEach(element=>{
                          if(element.pId!=null){
                            if(element.pId[0]=="c"){
                              dataConfigIds.push(element.id);
                            }else if(element.pId[0]=="d"){
                              deviceIds.push(element.id);
                            }
                          }
                        })
                        global.post("/admin/statisticsConfig/statisticsConfig/configGlobal?statisticsTypeId="+num+"&deviceIds="+deviceIds+"&dataConfigIds="+dataConfigIds,function(response){
                          if(response.success){
                              Dialog.toast("操作成功", {"intent":"success"});
                              app.initSCOP();
                            }else{
                              Dialog.toast(response.message, {"intent":"warn"});
                            }
                        })

                      } },
                      { id: "mybtn2", label: "取消", click: function () { } }
                    ]
                  });
                }
            });
            // 单个删除
            $(document).on('click', ".del-btn", function () {
                var type = $(this).attr("type");
                var dataConfigId = $(this).attr("dataConfigId");
                var rateTypeId=$(this).attr("rateTypeId");
                Dialog.open({
                    title: "<span class='aidicon aidicon-alert-circle-outline aidicon-warning'></span><span class='lineClamp2'>确定删除该信息吗？</span>",
                    width: 320,
                    height: 'auto',
                    modal: true,
                    content: '<div class="padding-left-large-5">您确定要删除吗？删除后状态不可恢复。</div>',
                    button: [
                        { id: "mybtn1", label: "确认", intent: "primary", focus: true, click: function () { 
                          if(type=="commonDataConfig"){
                            global.delete("/admin/statisticsConfig/dataConfig/delete/"+dataConfigId,response=>{
                              if(response.success){
                                Dialog.toast("操作成功", {"intent":"success"});
                                app.initCommonDataItem();
                              }else{
                                Dialog.toast(response.message, {"intent":"warn"});
                              }
                            })
                          }else if(type=="rateType"){
                            global.delete("/admin/statisticsConfig/powercostRateConfig/delete/"+rateTypeId,response=>{
                              if(response.success){
                                Dialog.toast("操作成功", {"intent":"success"});
                                app.initPowercostRate();
                              }else{
                                Dialog.toast(response.message, {"intent":"warn"});
                              }
                            })
                          }
                        } },
                        { id: "mybtn2", label: "取消", click: function () { } }
                    ]
                });
            });
            // 隐藏多选下拉
            $(document).on('click', '#dropdownSelect-treeSelect-multi29', function () {
              $("#treeDemo-30").parent(".dropdownSelect-menu").hide();
            })
            $(document).on('click', '#dropdownSelect-treeSelect-multi30', function () {
              $("#treeDemo-29").parent(".dropdownSelect-menu").hide();
            })
        }

    };
    return app;
});